package com.sudo.service.admin.task;

import com.sudo.common.enums.SysServerStatus;
import com.sudo.common.enums.SysStatus;
import com.sudo.common.utils.JsonUtil;
import com.sudo.dao.admin.entity.SysAutoRole;
import com.sudo.dao.admin.entity.SysServerNode;
import com.sudo.dao.admin.entity.SysUserBehavior;
import com.sudo.dao.admin.mapper.SysUserBehaviorMapper;
import com.sudo.rpc.api.annotation.TaskComponent;
import com.sudo.rpc.api.annotation.TaskNote;
import com.sudo.rpc.api.common.RpcConstant;
import com.sudo.service.admin.service.*;
import com.sudo.service.annotation.VerifyTaskRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;

@Slf4j
@TaskComponent
public class AdminTaskModule {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysUserBehaviorMapper sysUserBehaviorMapper;
    @Resource
    private SysAutoRoleService sysAutoRoleService;
    @Resource
    private SysServerNodeService sysServerNodeService;
    @Resource
    private SysRedisAuthService sysRedisAuthService;


    /**
     * 建议：按秒更新，用户行为记录
     */
    @VerifyTaskRequest
    @TaskNote(desc = "用户行为记录",params = "count(Integer,true,2,获取数据次数)")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void addUserBehaviorToMysqlFromRedis(Map<String,Object> paramMap) {
        int count = Integer.parseInt(paramMap.get("count").toString());
        List<SysUserBehavior> sysUserBehaviorList = new ArrayList<>();
        for (int i=0;i<count;i++){
            String jsonData = sysRedisAuthService.getRedisUserBehavior();
            if (StringUtils.isNotBlank(jsonData)) {
                SysUserBehavior sysUserBehavior = JsonUtil.jsonToPojo(jsonData, SysUserBehavior.class);
                sysUserBehaviorList.add(sysUserBehavior);
            }
        }
        if (CollectionUtils.isNotEmpty(sysUserBehaviorList)) {
            sysUserBehaviorMapper.insertList(sysUserBehaviorList);
        }
    }


    @VerifyTaskRequest
    @TaskNote(desc = "用户过期检测")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateAutoRoleStatus(){
        List<SysAutoRole> sysAutoRoleList = sysAutoRoleService.getExpirationAutoRole();

        int affectCount = 0;
        if (CollectionUtils.isNotEmpty(sysAutoRoleList)){
            for (SysAutoRole sysAutoRole : sysAutoRoleList) {
                if (SysStatus.ON.name().equals(sysAutoRole.getStatus())) {
                    affectCount += sysAutoRoleService.updateAutoRoleStatus(sysAutoRole);
                }
            }
        }
        log.info("更新过期用户状态{}条",affectCount);
    }

    @VerifyTaskRequest
    @TaskNote(desc = "服务在线检测")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void checkServerNode()  {
        List<SysServerNode> sysServerNodeList = sysServerNodeService.queryAllServerNodes();
        for (SysServerNode sysServerNode : sysServerNodeList) {
            String[] split = sysServerNode.getServer().split(":");
            try {
                Registry remoteRegistry = LocateRegistry.getRegistry(split[0], Integer.parseInt(split[1]));
                remoteRegistry.lookup(RpcConstant.registryCenter);
                sysServerNodeService.updateServerNodeStatus(sysServerNode.getServer(), SysServerStatus.ONLINE.name());
                log.info("服务{}在线",sysServerNode.getServer());
            } catch (RemoteException | NotBoundException e) {
                sysServerNodeService.updateServerNodeStatus(sysServerNode.getServer(), SysServerStatus.OFFLINE.name());
                log.error("服务{}离线",sysServerNode.getServer());
            }
        }
    }

}
